using System.Text.RegularExpressions;
using DiLu.Expansion.File.Configs;
using DiLu.Expansion.File.Operates.Minio.Configs;
using DiLu.Expansion.File.Operates.Minio.Tools;
using Minio.DataModel.Args;

namespace DiLu.Expansion.File.Operates.Minio;

public static class SearchMinioFile
{
    /// <summary>
    ///     搜索Minio文件信息
    /// </summary>
    /// <param name="config">搜索Minio配置</param>
    /// <returns></returns>
    public static async IAsyncEnumerable<FileInformation> SearchAsync(this SearchMinioFileConfig config)
    {
        if (!await config.MinioClient.CheckBucketAsync(config.BucketName)) yield break;

        string prefix;
        if (string.IsNullOrWhiteSpace(config.DirectoryFullPath) || config.DirectoryFullPath == "/")
            prefix = null;
        else
            prefix = config.DirectoryFullPath.StartsWith('/')
                ? $"{config.DirectoryFullPath[1..]}/"
                : $"{config.DirectoryFullPath}/";

        var listObjectsArgs = new ListObjectsArgs()
            .WithBucket(config.BucketName)
            .WithPrefix(prefix)
            .WithRecursive(config.SearchOption == SearchOption.AllDirectories);
        await foreach (var item in config.MinioClient.ListObjectsEnumAsync(listObjectsArgs))
        {
            if (!item.IsDir)
            {
                var lastPathIndex = item.Key.LastIndexOf('/');
                var fileName = lastPathIndex < 0 ? item.Key : item.Key[lastPathIndex..];
                if (!Regex.IsMatch(fileName, config.SearchPattern)) continue;
                var fullPath = lastPathIndex < 0 ? "/" : $"/{item.Key[..lastPathIndex]}";
                yield return new FileInformation(fileName, fullPath, Path.GetExtension(fileName), MimeTypes.GetMimeType(fileName));
            }

            await Task.Delay(0);
        }
    }
}